$(function () {
    var $selectpicker = $('select[data-toggle="selectpicker"]')
    var select_linkage = function ($obj, $next) {
        var refurl = $obj.data('refurl')
        var _setEmpty = function ($select) {
            var $_nextselect = $($select.data('nextselect'))

            if ($_nextselect && $_nextselect.length) {
                var emptytxt = $_nextselect.data('emptytxt') || ''
                $_nextselect.html('<option>' + emptytxt + '</option>').selectpicker('refresh')
                _setEmpty($_nextselect)
            }
        }

        if (($next && $next.length) && refurl) {
            var val = $obj.data('val');
            if (typeof val == 'undefined') val = $obj.val()
            $.ajax({
                type: 'get',
                dataType: 'json',
                url: refurl.replace('{value}', encodeURIComponent(val)),
                cache: false,
                data: {},
                success: function (json) {
                    if (!json) return
                    var html = '';
                    $.each(json, function (i) {
                        var value = json[i].value, label = json[i].label;
                        html += '<option value="' + value + '">' + label + '</option>'
                    })


                    if (!html) {
                        html = $next.data('emptytxt') || ''
                        html = '<option>' + html + '</option>'
                    }

                    $next.html(html).selectpicker('refresh')
                    _setEmpty($next)
                }
            })
        }
    }
    $selectpicker.each(function () {
        var $element = $(this)
        var options = $element.data()
        var $next = $(options.nextselect)

        $element.addClass('show-tick')
        if (!options.style) $element.data('style', 'btn-default')
        if (!options.width) $element.data('width', 'auto')
        if (!options.container) $element.data('container', 'body')
        else if (options.container == true) $element.attr('data-container', 'false').data('container', false)

        $element.selectpicker()

        if ($next && $next.length && (typeof $next.data('val') != 'undefined'))
            select_linkage($element, $next)
    })
    $selectpicker.change(function () {
        var $element = $(this)
        var $nextselect = $($element.data('nextselect'))
        select_linkage($element, $nextselect)
    })

})